package com.seele.tigerwallet.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.j256.ormlite.dao.GenericRawResults;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.async.DaoTask;
import com.seele.tigerwallet.model.MarketModel;
import com.seele.tigerwallet.ui.activtiy.AddMoreActivity;
import com.seele.tigerwallet.ui.adapter.MarketAdapter;
import com.seele.tigerwallet.ui.base.ToolbarFragment;
import com.seele.tigerwallet.ui.callback.DaoTaskListener;
import com.seele.tigerwallet.ui.event.AddMoreEvent;
import com.seele.tigerwallet.ui.event.ExchangeEvent;
import com.seele.tigerwallet.ui.event.MessageEvent;
import com.seele.tigerwallet.ui.event.SortEvent;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.ui.orm.GenericRowMapper;
import com.seele.tigerwallet.ui.utils.SPUtils;
import com.seele.tigerwallet.ui.utils.SqlUtil;
import com.seele.tigerwallet.ui.views.EmpteyView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import retrofit2.Call;

import static android.support.v4.widget.SwipeRefreshLayout.*;


/**
 * @Author: 郑波
 * @Time: 2018/6/7 19:57
 * @Description: 行情界面
 */
public class MarketFragment extends ToolbarFragment implements View.OnClickListener {

    //TODO 数据库需要优化
    private RecyclerView mRecyclerView;
    private MarketAdapter mMarketAdapter;
    private static MarketFragment marketFragment;
    private ImageView mIconImg;
    private List<MarketModel> mMarketModelList;
    private TextView mNewPriceTv;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TextView mTitle;
    private LinearLayout mAddLinearLayout;
    private View mSpliteView;
    private ItemDragAndSwipeCallback mItemDragAndSwipeCallback;
    private ItemTouchHelper mItemTouchHelper;
    private List<MarketModel> mResponse;
    private boolean isResume;


    public static MarketFragment newInstanec() {
        if (marketFragment == null) {
            marketFragment = new MarketFragment();
        }
        return marketFragment;
    }

    @Override
    public void onResume() {
        isResume = true;
        super.onResume();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_market;
    }

    protected void initView() {
        mTitle = $f(R.id.title_tv);
        mTitle.setText(getString(R.string.main_market));
        mSpliteView = $f(R.id.split_view2);
        mSpliteView.setVisibility(GONE);
        mAddLinearLayout = $f(R.id.add_ll);
        mIconImg = $f(R.id.add_icon);
        mIconImg.setImageDrawable(getResources().getDrawable(R.drawable.icon_add));
        mAddLinearLayout.setOnClickListener(this);
        mAddLinearLayout.setVisibility(VISIBLE);

        //注册EventBus
        if (!isRegistered()) {
            EventBus.getDefault().register(this);
        }
        mRecyclerView = $f(R.id.market_recyclerView);
        mNewPriceTv = $f(R.id.new_price_tv);
        //设置单位
        setPrice();

        mSwipeRefreshLayout = $f(R.id.swipeRefreshLayout);
        setAdapter();

        mSwipeRefreshLayout.setColorSchemeResources(R.color.color_63D0AB, R.color.color_FC6262);
        mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
//                mSwipeRefreshLayout.setEnabled(true);
                if (null!=mMarketModelList&&mMarketModelList.size()>0){
                    handlerData();
                }else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    },500);
                }
            }
        });


        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int topRowVerticalPosition2 = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                boolean topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0);
                topRowVerticalPosition = topRowVerticalPosition2 >= 0;
                mSwipeRefreshLayout.setEnabled(topRowVerticalPosition);
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        //加载本地数据
        onLoadlocal();

    }

    OnItemDragListener listener = new OnItemDragListener() {
        @Override
        public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
            android.util.Log.d("TAG", "drag start");
            BaseViewHolder holder = ((BaseViewHolder) viewHolder);

            holder.setBackgroundRes(R.id.item_rv, R.drawable.item_elevation_bg);
//            holder.setBackgroundColor(R.id.item_rv, getResources().getColor(R.color.color_F1F1F1));
        }

        @Override
        public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
            android.util.Log.d("TAG", "move from: " + source.getAdapterPosition() + " to: " + target.getAdapterPosition());
        }

        @Override
        public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
            android.util.Log.d("TAG", "drag end");
            BaseViewHolder holder = ((BaseViewHolder) viewHolder);
            holder.setBackgroundRes(R.id.item_rv, R.drawable.item_selector);
            //保存数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //保存数据
                    sortList();
                }
            }).start();


        }
    };

    /**
     * 排序保存
     */
    private void sortList() {
        if (null != mMarketModelList && mMarketModelList.size() > 0) {
            for (int i = 0; i < mMarketModelList.size(); i++) {
                mMarketModelList.get(i).position = i;
                mMarketModelList.get(i).isOpen = true;
                DaoManager.saveOrUpdate(mMarketModelList.get(i));
            }

        }

//        com.seele.tigerwallet.async.Log.e("sortList", "::" + GsonUtil.toJsonString(mMarketModelList));
    }


    //绑定适配器
    private void setAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mMarketAdapter = new MarketAdapter(mMarketModelList);
        mRecyclerView.setAdapter(mMarketAdapter);
        mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mMarketAdapter);
        mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mMarketAdapter.enableDragItem(mItemTouchHelper);
        mMarketAdapter.setOnItemDragListener(listener);

    }

    private void setPrice() {
        mNewPriceTv.setText(SPUtils.getNewPrice());
    }


    /**
     * 加载本地数据
     */
    private void onLoadlocal() {
        //是否已经请求过默认是数据
        try {
//            mMarketModelList = DaoManager.getMarketDao().queryForAll();
            GenericRawResults<MarketModel> rawResults = DaoManager.getMarketDao().queryRaw(SqlUtil.queryMarketFromAsc(), new GenericRowMapper(MarketModel.class));
            mMarketModelList = rawResults.getResults();
            rawResults.close();
            if (null != mMarketModelList && mMarketModelList.size() > 0) {
                handlerData();
            } else {
                //第一次请求数据
                getFirst();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x963:
                    try {

                        if (null != mMarketModelList && mMarketModelList.size() > 0) {
                            //设置单位
                            setPrice();
                            handlerData();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 0x98:
                    try {
                        handleResponse(mResponse);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    /**
     * 请求行情列表数据
     *
     * @param stringBuilder
     */
    private void initData(StringBuilder stringBuilder) {
        if (null == stringBuilder) {
            return;
        }
        if (stringBuilder.length() > 0) {
            APIModule.getApi()
                    .quotationDynamic(stringBuilder.toString())
                    .enqueue(new APIListCallBack<MarketModel>() {
                        @Override
                        protected void onResponse(List<MarketModel> response) {
                            mResponse = response;
                            handler.sendEmptyMessage(0X98);

//                            Message message = new Message();
//                            message.obj = response;
//                            message.what=0X98;
//                            handler.sendMessage(message);


                        }

                        @Override
                        protected void onResponseError(APIException e) {
                            mSwipeRefreshLayout.setRefreshing(false);

                        }

                        @Override
                        protected void onFailureError(Call<String> call, Throwable t) {
                            mSwipeRefreshLayout.setRefreshing(false);

                        }


                    });
        }


    }

    private void handleResponse(List<MarketModel> response) {
        if (null != mMarketModelList && mMarketModelList.size() > 0 && null != response && response.size() > 0) {
            for (MarketModel marketModel : mMarketModelList) {
                for (MarketModel model : response) {
                    if (marketModel.id == model.id) {
                        marketModel.change = model.change;
                        marketModel.price = model.price;
                    }
                }
            }
            sortList();
            mMarketAdapter.setNewData(mMarketModelList);
            mMarketAdapter.notifyDataSetChanged();

        }
        mSwipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 查询本地数据
     */
    @NonNull
    private void handlerData() {
        StringBuilder stringBuilder = new StringBuilder();
        //查询本地数据
        try {
            for (int i = 0; i < mMarketModelList.size(); i++) {
                stringBuilder.append(mMarketModelList.get(i).id);
                if (i != mMarketModelList.size() - 1) {
                    stringBuilder.append(",");
                }
            }
            mMarketAdapter.setNewData(mMarketModelList);
            mMarketAdapter.notifyDataSetChanged();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //网络请求参数
        if (!TextUtils.isEmpty(stringBuilder.toString())) {
            initData(stringBuilder);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        try {
            if (event instanceof AddMoreEvent) {//添加新的资产
                final AddMoreEvent addMoreEvent = (AddMoreEvent) event;
                final List<MarketModel> marketModels = addMoreEvent.mMarketModelList;
                if (null != marketModels && marketModels.size() > 0) {
                    List<Integer> list = new ArrayList<>();
                    for (MarketModel assetsModel : marketModels) {
                        list.add(assetsModel.id);
                    }


                    if (null != mMarketModelList && mMarketModelList.size() > 0) {
                        DaoTask daoTask = new DaoTask(list, mMarketModelList);
                        daoTask.setDaoTaskListener(new DaoTaskListener() {
                            @Override
                            public void onResponse() {
                                mMarketModelList = marketModels;
//                                saveMarket();
                                handlerData();
                            }
                        });
                        daoTask.execute();
                    } else {
                        mMarketModelList = marketModels;
                        handlerData();
                    }
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //删除数据库所有的值
                                DaoManager.getMarketDao().updateRaw(getSql());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    mMarketModelList = marketModels;
                    handlerData();
                }

            } else if (event instanceof SortEvent) {//排序
//                SortEvent sortEvent = (SortEvent) event;
//                List<MarketModel> modelList = sortEvent.mMarketModelList;
//                if (null != mMarketModelList && mMarketModelList.size() > 0 && null != modelList && modelList.size() > 0) {
//                    for (MarketModel marketModel : mMarketModelList) {
//                        for (MarketModel model : modelList) {
//                            if (marketModel.symbol.equals(model.symbol)) {
//                                marketModel.position = model.position;
//                            }
//                        }
//                    }
//                    mMarketAdapter.setNewData(mMarketModelList);
//                    mMarketAdapter.notifyDataSetChanged();
//                }
            } else if (event instanceof ExchangeEvent) {//汇率改变
//                setPrice();
//                if (null != mMarketAdapter) {
//                    mMarketAdapter.notifyDataSetChanged();
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_ll:
                if (null != mMarketModelList && mMarketModelList.size() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AddMoreActivity.class.getSimpleName(), (Serializable) mMarketModelList);
                    startActivity(AddMoreActivity.class, bundle);
                } else {
                    startActivity(AddMoreActivity.class);
                }
                break;
        }
    }


    @Override
    public void onDestroy() {
        if (isRegistered()) {
            EventBus.getDefault().unregister(this);
        }
//        saveMarket();

        super.onDestroy();
    }


    /**
     * 保存行情数据
     */
    private void saveMarket() {
        try {
            if (null != mMarketModelList && mMarketModelList.size() > 0) {
                for (MarketModel marketModel : mMarketModelList) {
                    try {
                        DaoManager.saveOrUpdate(marketModel);
                        //  DaoManager.getMarketDao().create(marketModel);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onHiddenChanged(final boolean hidden) {
        if (isResume && !hidden) {
            handler.sendEmptyMessageDelayed(0x963, 500);
        }
    }

    /**
     * 判断是够注册了 EventBus
     *
     * @return
     */

    private boolean isRegistered() {
        return EventBus.getDefault().isRegistered(this);
    }

    /**
     * 清除表中数据
     *
     * @return
     */
    public String getSql() {
        return "delete from t_market";
    }

    /**
     * 默认加载行情列表
     */
    public void getFirst() {
        APIModule
                .getApi()
                .quotationFixlist()
                .enqueue(new APIListCallBack<MarketModel>() {
                    @Override
                    protected void onResponse(List<MarketModel> response) {
                        if (null != response && response.size() > 0) {
                            mMarketModelList = response;
                            for (int i = 0; i < mMarketModelList.size(); i++) {
                                response.get(i).isOpen = true;
                                //保存数据数据库
                            }
                            sortList();
                            mMarketAdapter.setNewData(mMarketModelList);
                            mMarketAdapter.notifyDataSetChanged();
                        }

                    }

                    @Override
                    protected void onResponseError(APIException e) {

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {

                    }


                });
    }
}
